package com.concurrent.threadpool;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;

/**
 * @Date 2020/7/13 11:16
 * @Author admin 类比线程池原理
 * @Description
 */
public class MyThreadPool {
    //利用阻塞队列实现生产者-消费者模式
    BlockingQueue<Runnable> workQueue;
    //保存内部工作线程
    List<WorkerThread> threads = new ArrayList<>();

    MyThreadPool(int poolSize,BlockingQueue workQueue){
        this.workQueue = workQueue;
        //创建工作线程
        for (int i = 0; i < poolSize; i++) {
            WorkerThread worker = new WorkerThread();
            worker.start();
            threads.add(worker);
        }
    }
    //提交任务
    void execute(Runnable command){
        try {
            workQueue.put(command);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
    /**
     * 工作线程负责消费并执行任务
     */
    class WorkerThread extends Thread{
        @Override
        public void run(){
            //循环取任务并执行
            while(true){
                Runnable task = null;//从队列中获取工作线程 并且执行
                try {
                    task = workQueue.take();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                task.run();
            }
        }
    }

    public static void main(String[] args) {
        //创建有界阻塞队列
        BlockingQueue<Runnable> workQueue = new LinkedBlockingQueue<>(2);
        //创建线程池
        MyThreadPool myThreadPool = new MyThreadPool(10,workQueue);
        //提交任务
        myThreadPool.execute(()->{
            System.out.println("hello");
        });
    }

}
